package com.yhsimon.controller;


import com.yhsimon.entity.Commodity;
import com.yhsimon.entity.CommodityVO;
import com.yhsimon.feign.CommodityFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

//@RestController
@Controller
@RequestMapping("/commodity")
public class CommodityHandler {

    @Autowired
    private CommodityFeign commodityFeign;

    @GetMapping("/findAll")
    @ResponseBody
    public CommodityVO findAll(@RequestParam("page") int page, @RequestParam("limit") int limit) {
        return commodityFeign.findAll(page, limit);
    }

    @GetMapping("/findByName/{name}")
    @ResponseBody
    public CommodityVO findByName(@RequestParam("page") int page,@RequestParam("limit") int limit,@PathVariable("name") String name){
        return commodityFeign.findByName(page, limit,name);
    }

    @GetMapping("/redirect/{location}")
    public String redirect(@PathVariable("location") String location) {
        return location;
    }

    @GetMapping("/deleteById/{id}")
    public String deleteById(@PathVariable("id") int id) {
        commodityFeign.deleteBytId(id);
        return "redirect:/account/redirect/commodity_manage";
    }


    @GetMapping("/findById/{id}")
    public String findById(@PathVariable("id") int id, Model model) {
        model.addAttribute("commodity", commodityFeign.findById(id));
        model.addAttribute("list", commodityFeign.findAllTypes());
        return "commodity_update";
    }

    @GetMapping("/findAllTypes")
    public ModelAndView findAllTypes() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("commodity_add");
        modelAndView.addObject("list", commodityFeign.findAllTypes());
        return modelAndView;
    }

    @PostMapping("/update")
    public String update(Commodity commodity) {
        commodityFeign.update(commodity);
        return "redirect:/account/redirect/commodity_manage";
    }

    @GetMapping("/prepareSave")
    public String prepareSave(Model model) {
        model.addAttribute("list", commodityFeign.findAllTypes());
        return "commodity_add";
    }

    @PostMapping(value = "/save")
    public String save(Commodity commodity) {
        commodityFeign.save(commodity);
        return "redirect:/account/redirect/commodity_manage";
    }


}
